import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  NavBar,
  Form,
  Input,
  TextArea,
  Radio,
  Image,
  Divider,
  Button,
  Dialog,
  Toast,
  Popup
} from 'antd-mobile';
import { AddOutline, RightOutline } from 'antd-mobile-icons';
import './OrderCreate.css';
import { useRequest } from 'ahooks';
import { addOrder } from '../../api/store';
// 订单创建页面
const OrderCreate = () => {
  const navigate = useNavigate();
  const [orderItems, setOrderItems] = useState([]);
  const [totalPrice, setTotalPrice] = useState(0);
  const [totalCount, setTotalCount] = useState(0);
  const [addressVisible, setAddressVisible] = useState(false);
  const [paymentVisible, setPaymentVisible] = useState(false);
  const [selectedAddress, setSelectedAddress] = useState(null);
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [addresses, setAddresses] = useState([]);
  const [form] = Form.useForm();
  const {runAsync: submitOrderRequest} = useRequest(addOrder, {manual: true});

  // 加载订单数据
  useEffect( () => {
    // 从本地存储获取临时订单项
    const storedOrderItems = JSON.parse(localStorage.getItem('tempOrderItems') || '[]');

    if (storedOrderItems.length === 0) {
      Toast.show({
        icon: 'fail',
        content: '订单数据不存在',
      });
      navigate('/cart');
      return;
    }

    setOrderItems(storedOrderItems);

    // 计算总价和总数量
    const total = storedOrderItems.reduce((sum, item) => sum + item.price * item.quantity, 0);
    const count = storedOrderItems.reduce((sum, item) => sum + item.quantity, 0);
    setTotalPrice(total);
    setTotalCount(count);

    // 模拟加载收货地址
    setTimeout(() => {
      const addressData = [
        {
          id: 1,
          name: '张三',
          phone: '13800138000',
          province: '广东省',
          city: '深圳市',
          district: '南山区',
          address: '科技园南路XX号',
          isDefault: true
        },
        {
          id: 2,
          name: '李四',
          phone: '13900139000',
          province: '广东省',
          city: '广州市',
          district: '天河区',
          address: '天河路XX号',
          isDefault: false
        }
      ];

      setAddresses(addressData);
      setSelectedAddress(addressData.find(addr => addr.isDefault) || addressData[0]);
    }, 500);
  }, [navigate]);

  // 返回上一页
  const back = () => {
    Dialog.confirm({
      content: '确定要放弃下单吗？',
      onConfirm: () => {
        navigate(-1);
      },
    });
  };

  // 选择地址
  const selectAddress = (address) => {
    setSelectedAddress(address);
    setAddressVisible(false);
  };

  // 选择支付方式
  const selectPayment = (method) => {
    setPaymentMethod(method);
    setPaymentVisible(false);
  };

  // 提交订单
  const submitOrder =async  () => {
    if (!selectedAddress) {
      Toast.show({
        icon: 'fail',
        content: '请选择收货地址',
      });
      return;
    }

    // 获取备注信息
    const values = form.getFieldsValue();

    // 创建订单
    const order = {
      id: Date.now().toString(),
      orderItems,
      totalPrice,
      totalCount,
      address: selectedAddress,
      paymentMethod,
      remark: values.remark || '',
      status: 'pending',
      createTime: new Date().toISOString()
    };

    // 保存订单到本地存储
    await submitOrderRequest(order);

    // 如果是从购物车下单，清除已下单的商品
    const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
    const orderItemIds = orderItems.map(item => item.id);
    const newCartItems = cartItems.filter(item => !orderItemIds.includes(item.id));
    localStorage.setItem('cartItems', JSON.stringify(newCartItems));

    // 清除临时订单项
    localStorage.removeItem('tempOrderItems');

    // 跳转到支付页面
    navigate(`/order/payment/${order.id}`);
  };

  // 渲染地址选择
  const renderAddressSelect = () => {
    return (
      <div className="order-section" onClick={() => setAddressVisible(true)}>
        {selectedAddress ? (
          <div className="selected-address">
            <div className="address-info">
              <div className="address-header">
                <span className="address-name">{selectedAddress.name}</span>
                <span className="address-phone">{selectedAddress.phone}</span>
              </div>
              <div className="address-detail">
                {`${selectedAddress.province}${selectedAddress.city}${selectedAddress.district}${selectedAddress.address}`}
              </div>
            </div>
            <div className="address-arrow">
              <RightOutline />
            </div>
          </div>
        ) : (
          <div className="add-address">
            <AddOutline />
            <span>添加收货地址</span>
          </div>
        )}
      </div>
    );
  };

  // 渲染商品列表
  const renderOrderItems = () => {
    return (
      <div className="order-section">
        <div className="section-title">商品信息</div>
        <div className="order-items">
          {orderItems.map(item => (
            <div key={item.id} className="order-item">
              <div className="item-image">
                <Image
                  src={item.image}
                  fit='cover'
                  width={80}
                  height={80}
                />
              </div>
              <div className="item-info">
                <div className="item-name">{item.name}</div>
                <div className="item-price-qty">
                  <span className="item-price">¥{item.price.toFixed(2)}</span>
                  <span className="item-quantity">x{item.quantity}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="order-total">
          <span>共{totalCount}件商品</span>
          <span>合计: <span className="total-price">¥{totalPrice.toFixed(2)}</span></span>
        </div>
      </div>
    );
  };

  // 渲染支付方式选择
  const renderPaymentSelect = () => {
    return (
      <div className="order-section" onClick={() => setPaymentVisible(true)}>
        <div className="section-title">支付方式</div>
        <div className="payment-method">
          <span>
            {paymentMethod === 'alipay' ? '支付宝' : paymentMethod === 'wechat' ? '微信支付' : '货到付款'}
          </span>
          <RightOutline />
        </div>
      </div>
    );
  };

  // 地址选择弹窗
  const renderAddressPopup = () => {
    return (
      <Popup
        visible={addressVisible}
        onMaskClick={() => setAddressVisible(false)}
        position='bottom'
        bodyStyle={{ height: '60vh' }}
      >
        <div className="popup-header">
          <div className="popup-title">选择收货地址</div>
          <div className="popup-close" onClick={() => setAddressVisible(false)}>关闭</div>
        </div>
        <div className="address-list">
          {addresses.map(address => (
            <div
              key={address.id}
              className={`address-item ${selectedAddress?.id === address.id ? 'active' : ''}`}
              onClick={() => selectAddress(address)}
            >
              <div className="address-header">
                <span className="address-name">{address.name}</span>
                <span className="address-phone">{address.phone}</span>
                {address.isDefault && <span className="address-default">默认</span>}
              </div>
              <div className="address-detail">
                {`${address.province}${address.city}${address.district}${address.address}`}
              </div>
            </div>
          ))}
          <div className="add-new-address" onClick={() => Toast.show('添加新地址功能开发中')}>
            <AddOutline />
            <span>添加新地址</span>
          </div>
        </div>
      </Popup>
    );
  };

  // 支付方式选择弹窗
  const renderPaymentPopup = () => {
    return (
      <Popup
        visible={paymentVisible}
        onMaskClick={() => setPaymentVisible(false)}
        position='bottom'
        bodyStyle={{ height: '30vh' }}
      >
        <div className="popup-header">
          <div className="popup-title">选择支付方式</div>
          <div className="popup-close" onClick={() => setPaymentVisible(false)}>关闭</div>
        </div>
        <div className="payment-list">
          <div
            className={`payment-item ${paymentMethod === 'alipay' ? 'active' : ''}`}
            onClick={() => selectPayment('alipay')}
          >
            <div className="payment-icon alipay-icon">支</div>
            <div className="payment-name">支付宝</div>
            {paymentMethod === 'alipay' && <div className="payment-selected">✓</div>}
          </div>
          <div
            className={`payment-item ${paymentMethod === 'wechat' ? 'active' : ''}`}
            onClick={() => selectPayment('wechat')}
          >
            <div className="payment-icon wechat-icon">微</div>
            <div className="payment-name">微信支付</div>
            {paymentMethod === 'wechat' && <div className="payment-selected">✓</div>}
          </div>
          <div
            className={`payment-item ${paymentMethod === 'cod' ? 'active' : ''}`}
            onClick={() => selectPayment('cod')}
          >
            <div className="payment-icon cod-icon">付</div>
            <div className="payment-name">货到付款</div>
            {paymentMethod === 'cod' && <div className="payment-selected">✓</div>}
          </div>
        </div>
      </Popup>
    );
  };

  return (
    <div className="order-create-container">
      {/* 导航栏 */}
      <NavBar onBack={back}>确认订单</NavBar>

      <Form form={form} layout='horizontal'>
        {/* 收货地址 */}
        {renderAddressSelect()}

        {/* 商品信息 */}
        {renderOrderItems()}

        {/* 支付方式 */}
        {renderPaymentSelect()}

        {/* 订单备注 */}
        <div className="order-section">
          <div className="section-title">订单备注</div>
          <Form.Item name="remark">
            <TextArea
              placeholder='请输入订单备注信息（选填）'
              maxLength={100}
              showCount
              rows={3}
            />
          </Form.Item>
        </div>
      </Form>

      {/* 底部空间 */}
      <div className="order-bottom-space"></div>

      {/* 底部结算栏 - 重构为原生HTML */}
      <div className="order-fixed-footer">
        <div className="footer-total">
          <span className="total-label">实付款:</span>
          <span className="total-price">¥{totalPrice.toFixed(2)}</span>
        </div>
        <div className="footer-submit">
          <button className="submit-btn" onClick={submitOrder}>
            提交订单
          </button>
        </div>
      </div>

      {/* 地址选择弹窗 */}
      {renderAddressPopup()}

      {/* 支付方式弹窗 */}
      {renderPaymentPopup()}
    </div>
  );
};

export default OrderCreate; 